/**
 * 菜单
 * */
//获取路径uri
var pathUri=window.location.href;

const URL = (function () {

    /**
     * 添加uri参数
     * @param string uri
     * @param string key
     * @param string value
     */
    let addQueryParameter = function (uri, key, value) {
        let re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        let separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
            if(value == null || value.length == 0){
                return uri.replace(re, '$1');
            }
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        }
        else {
            if(value == null || value.length == 0){
                return uri;
            }
            return uri + separator + key + "=" + value;
        }
    };

    /**
     * 读取url参数
     * @param uri
     * @param name
     */
    let getQueryParameter = function (uri, name) {
        if(! (uri && name)){return null;}
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        let index = uri.indexOf('?');
        if(index == -1){return null;}
        let r = uri.substr(index + 1).match(reg); //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
        return null;
    };

    return {
        currentUrl: window.location.href,
        addQueryParameter: addQueryParameter,
        getQueryParameter: getQueryParameter
    }

})();

/**
 * 读取面页导航hash并召开导航列表
 * @type {{}|{getUrl, thisNav, hash}}
 */
let Hash = (function () {
    // let nav = location.nav.replace(/^#nav=/, '');
    // console.log('init hash', location.hash);
    let nav, thisNav;
    /*if(location.hash){ //如果有hash，则使用hash
        let argList= location.hash.split('#');
        if(argList[1]){
            nav = argList[1].replace('nav=', '');
        }
        if(argList[2]) {
            thisNav = argList[2].replace('this_nav', '');
        }

    }else{//否则使用url
        let url = window.location.href;
        nav = URL.getQueryParameter(url,'nav');
        thisNav =URL.getQueryParameter(url,'nav_this');
    }*/

    let url = window.location.href;
    nav = URL.getQueryParameter(url,'nav');
    thisNav =URL.getQueryParameter(url,'nav_this');

    let hash = {};
    if(nav){
        let _hashList = nav.split(',');
        // console.log('_hashList', _hashList);
        for(let i in _hashList){
            hash[_hashList[i]] = true;
        }
        //展开导航并
        $.each($('.layui-side ul.layui-nav li.layui-nav-item'), function () {
            let hashValue = $(this).attr('hash');
            // console.log('each nav value', hashValue);
            if(hashValue && hashValue in hash){
                $(this).addClass('layui-nav-itemed');
            }

        });
    }

    //高亮选择的项
    let _thisNavList;
    if(thisNav){
        _thisNavList = thisNav.split(',');
        if(_thisNavList.length == 2){
            let thisIndex = parseInt(_thisNavList[1]);
            let li = $('.layui-side ul.layui-nav li.layui-nav-item[hash=' + _thisNavList[0] + ']');
            if(li.length != 0){
                li.find('.layui-nav-child>dd').eq(thisIndex).addClass('layui-this');
            }
        }
    }

    _thisNavList = _thisNavList || [];

    let getUrl = function (url) {
        let newUrl = URL.addQueryParameter(url, 'nav', Object.keys(this.hash).join(','));
        newUrl = URL.addQueryParameter(newUrl, 'nav_this', this.thisNav.join(','));
        return newUrl;
    };

    let getHash = function () {
        let hash = Object.keys(this.hash);
        return [
            hash.length >0?'nav='+ hash.join(','):'',
            this.hash.length >0?'#nav_this=' + this.thisNav.join(','): ''
        ].join('');
    };


    return {
        hash: hash,
        thisNav: _thisNavList,
        getUrl: getUrl,
        getHash: getHash
    };

})();


// console.log("pathUrl:"+pathUri);
$(function(){
    layui.use(['element'], function(){
        var element = layui.element;

        let onNavigator = function(){
            //记录导航位置
            element.on('nav(main-nav)', function(dom){
                // console.log(data);
                let parent = $(dom).parent();
                if(parent.length == 0){return;}
                let hashValue = parent.attr('hash');
                if(!hashValue){return;}

                if(parent.hasClass('layui-nav-itemed')){
                    Hash.hash[hashValue] = true;
                }else{
                    delete Hash.hash[hashValue];
                }
                // location.hash = 'nav=' + Object.keys(_hash).join(',');

                // let newUrl = Hash.getUrl(window.location.href);
                // //向当前url添加参数，没有历史记录
                // window.history.replaceState({
                //     path: newUrl
                // }, '', newUrl);
                // console.log('href', location.href);
                location.hash = Hash.getHash();
                console.log('hash', location.hash);

                // console.log(data.show); //得到当前面板的展开状态，true或者false
                // console.log(data.title); //得到当前点击面板的标题区域DOM对象
                // console.log(data.content); //得到当前点击面板的内容区域DOM对象
            });


            //监听面页跳转
            $('.layui-side ul.layui-nav li.layui-nav-item dd>a').on('click', function () {
                let url = $(this).attr('href');
                if(url){
                    let li = $(this).parent().parent().parent();
                    let hashValue = li.attr('hash');
                    if(hashValue){
                        Hash.thisNav = new Array(2);
                        Hash.thisNav[0] = hashValue;
                        Hash.thisNav[1] = $(this).parent().index();
                        $(this).attr('href', Hash.getUrl(url));
                    }
                }
            })
        };

        // onNavigator();
        // 左侧导航区域（可配合layui已有的垂直导航）
        $.ajax({
            url: '/auth/getUserPerms',
            success: (res)=>{
                if(res.code == 0){
                    initMenu(res.data);
                    // getMenus(res.data);
                    element.render('nav', 'MAIN-NAV')

                    // element.render('nav'); ////重新对导航进行渲染
                }else{
                    // window.location.href="/";
                    console.log("权限读取出错")
                }
            }
        });



    });
});

/**
 *
 * @param {Array} permissions
 */
let initMenu = function (permissions) {
    let LEAF_TEMPLATE = `<dd><a href="{page}">{name}</a></dd>`;
    let NONE_LEAF_TEMPLATE = `<li class="layui-nav-item" hash="{id}">
            <a href="javascript:;">
                {name}<span class="layui-nav-more"></span>
            </a>
            <dl class="layui-nav-child"></dl>
        </li>`;

    let root = $('#MAIN-NAV');
    let domTree = {};
    let permissionsSet = {};
    for(let i in permissions){
        permissionsSet[permissions[i].id] = permissions[i];
    }

    const PATH_RUI = window.location.href;

    //此处扫描两次，可以解决依赖问题，比如a是b的子节点，但是创建a时b还没有创建
    for(let i=0; i<2; i++){
        permissions.forEach((each)=>{
            if(each.istype !=0) {return;} //过滤掉功能组
            if(each.id in domTree){return;}
            if(each.pid && each.pid >0){
                let parentDom = domTree[each.pid];
                if(parentDom){
                    let dl = parentDom.find('>dl.layui-nav-child:first');
                    if(!dl.length){
                        //没有找到dl标签,将父dom升级为非叶子节点
                        parentDom = $(NONE_LEAF_TEMPLATE.format(permissionsSet[each.pid])).replaceAll(parentDom);
                        domTree[each.pid] = parentDom;
                        dl = parentDom.find('>dl.layui-nav-child:first');
                    }
                    let child = $(LEAF_TEMPLATE.format(each));
                    dl.append(child);
                    domTree[each.id] = child;
                    //判断选中状态
                    if(PATH_RUI.indexOf(each.page)>0){
                        parentDom.addClass("layui-nav-itemed");
                        child.addClass('layui-this');
                    }
                    // domTreeFlag[each.id] = true;
                }
            }else{
                //根节点
                let child = $(LEAF_TEMPLATE.format(each));
                root.append(child);
                // domTreeFlag[each.id] = true;
                domTree[each.id] = child;
            }
        });
    }

    // console.log('domTreeFlag', domTreeFlag);
    // console.log('domTree', domTree);

};


function updateUsePwd(){
    layer.open({
        type:1,
        title: "修改密码",
        fixed:false,
        resize :false,
        shadeClose: true,
        area: ['450px'],
        content:$('#useDetail')
    });
}



/**
 * 导航条操作
 * @type {{show}}
 */
const GUIDE = (function () {
    var menu = $('div.layui-side:first');
    var header = $('div.layui-header:first');

    var cache = {
        body:{}
    };

    var fShow = true;

    var show = function (flag) {
        if(flag){
            var footer = $('div.layui-footer:last');
            $('div.layui-body:first').css('left' ,menu.css('width') || '180px').css('bottom' ,footer.css('height') || '44px');
            $(menu).show();
            footer.show();
        }else{
            //面页主体
            var body = $('div.layui-body:first');
            var footer = $('div.layui-footer:last');
            cache['body'].left = menu.css('width');
            cache['body'].bootom = footer.css('height');

            body.css('left', '0px');
            body.css('bottom', '0px');
            menu.hide();

            footer.hide();
        }
        fShow = flag;
    };

    //菜单切换按钮点击
    $('#GuideSwitchButton').on('click', function () {
        show(!fShow);
    });

    return {
        show: show
    };

})();